package pl.edu.agh.uddiProxy.client;

import java.util.Map;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.HistoryListener;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.gwtent.acegi.client.UserLoginRpc;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Application implements EntryPoint {
	public static final String PRICE_PARAMETER = "price";
	
	private ParametersSearchPanel parametersSearchPanel = new ParametersSearchPanel();
	
	public void onModuleLoad() {
		
		getUser();
		RootPanel.get("panel").add(parametersSearchPanel);
		
		final SearchServiceAsync searchServiceAsync = SearchService.Util.getInstance();
		searchServiceAsync.getParametersMap(new AsyncCallback<Map<String, Parameter>>() {
			public void onSuccess(Map<String, Parameter> map) {
				parametersSearchPanel.setMap(map);
			};
			
			public void onFailure(Throwable throwable) {
				Window.alert(throwable.getMessage());
			}
		});
		
		History.addHistoryListener(new HistoryListener() {
		
			public void onHistoryChanged(String string) {
				if (!string.startsWith("download") && !string.startsWith("tModelKey")) {
					RootPanel.get("panel").clear();
					RootPanel.get("panel").add(parametersSearchPanel);
				}
			}
		});
		
		History.fireCurrentHistoryState();
		
	}
	
	private void getUser() {
		UserLoginRpc.Util.getInstance().getCurrentUserName(
			new AsyncCallback<String>() {

				public void onFailure(Throwable caught) {
					Window.alert(caught.getMessage());
				}

				public void onSuccess(final String username) {
					HTML html = new HTML("<a href=#>Logout "+ username + "</a>");
					html.addClickListener(new ClickListener() {
					
						public void onClick(Widget arg0) {
							UserLoginRpc.Util.getInstance().logout(username, new AsyncCallback<Void>() {
							
								public void onSuccess(Void arg0) {
									Window.open("../index.html", "_self", "");
								}
							
								public void onFailure(Throwable arg0) {
							
								}
							});					
						}
					});
					HorizontalPanel panel = new HorizontalPanel();
					panel.setSize("100%", "100%");
					panel.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);
					panel.add(html);
					RootPanel.get("logout").add(panel);
					
					RootPanel.get("adminLI").setVisible(username.equals("admin"));
				}
			});
	}
}
